package com.share.web.action.site.navigation;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.share.bean.site.SiteNaviItem;
import com.share.commons.freemarker.FreeMarkerToHtmlUtil;
import com.share.service.site.navigation.SiteNaviItemManager;
import com.share.web.action.base.BaseActionSupport;

@Controller
@Scope("prototype")
public class SiteNaviItemAction extends BaseActionSupport {

	private static final long serialVersionUID = 1L;

	private SiteNaviItem sni;
	
	private String ids ;


	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

	@Resource
	private SiteNaviItemManager snim;

	public String addSiteNaviItem() {
		this.snim.save(sni);

		return SUCCESS;
	}

	public String querySiteNaviItem() {

		this.getBaseform().getRequest().setAttribute("naviItemList", this.snim.find());
		
		if("addNavi".equals(this.getBaseform().getType())) {
			return "addNavi" ;
		} else {
			return "queryAll";
		}
	}

	public String queryByIdSni() {
		this.getBaseform().getRequest().setAttribute("naviItem", this.snim.loadById(sni.getId()));
		
		if("loadNavi".equals(this.getBaseform().getType())) {
			return "loadNavi" ;
		} else {
			return "updateSni";
		}
	}
	
	public String exportHTML() throws Exception{
		try {
			
			String[] sinIds = ids.split(",") ;
			for(int i=0; i<sinIds.length; i++) {
				SiteNaviItem data = (SiteNaviItem)this.snim.loadById(Integer.parseInt(sinIds[i])) ;
				
				Map<String,Object> rootMap = new HashMap<String,Object>() ;
				rootMap.put("siteNaviItem",data) ;
				rootMap.put("path", this.getBaseform().getPath()) ;
				
				FreeMarkerToHtmlUtil.exportHtml(this.getBaseform().getRequest().getSession().getServletContext(), rootMap, "website/"+data.getTemplateName(), data.getExportHtmlName()) ;
			}
			FreeMarkerToHtmlUtil.exportHtml(this.getBaseform().getRequest().getSession().getServletContext(), null, "website/index.ftl", "default.html") ;
			
			this.getBaseform().getRequest().setAttribute("msg","生成HTML成功") ;
		} catch(Exception e) {
			this.getBaseform().getRequest().setAttribute("msg","生成HTML失败") ;
			e.printStackTrace() ;
		}
		
		return "msg" ;
	}
	
	public String updateSiteNI() {

		this.snim.update(sni) ;

		return SUCCESS;
	}
	
	public String deleteSiteNI() {

		this.snim.delete(sni.getId()) ;

		return SUCCESS;
	}

	public SiteNaviItem getSni() {
		return sni;
	}

	public void setSni(SiteNaviItem sni) {
		this.sni = sni;
	}

	public void setSnim(SiteNaviItemManager snim) {
		this.snim = snim;
	}

}
